import { message } from 'antd';
import request from '../request.js'


/**
 * 通过文件流blob实现文件下载
 * @name: downloadByBlob
 * @param {object} res 获取文件流请求返回的response
 */
export const downloadByBlob = async function (res) {
    let fileName = res.headers['content-disposition'].split('=');
    fileName = fileName[fileName.length - 1];
    fileName = fileName.replace(/(utf-8|')/gi, '').replace(/\+/g, ' ');
    fileName = decodeURI(fileName);
    if (window.navigator.msSaveBlob) {
        window.navigator.msSaveBlob(res.data, fileName);
        return;
    }
    const reader = new FileReader();
    reader.readAsDataURL(res.data);
    const url = await new Promise((resolve) => {
        reader.onload = function (e) {
            resolve(e.target.result);
        };
    });
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;

    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    link.parentNode.removeChild(link);
};

/**
 * 单文件下载
 * 先调用接口拿到文件流，再通过downloadByBlob方法进行文件下载
 * @name: downloadFile
 * @param {string} url 文件流请求路径
 * @param {object} params 文件流请求参数
 * @param {string} method 文件流请求方式，不传默认为get请求
 * @param {[]} headers 请求头数组
 * @return {boolean} isDownloadSuccess 是否下载成功
 */
export const downloadFile = async (url, params, method = 'GET', headers = []) => {
    try {
        const res = getFileBlob(url,params,{
            headers: headers
        },method)
        const resData = res?.data;
        const { size, type } = resData ?? {};
        const isDownloadSuccess = size && type && type !== 'application/json';
        const reader = new FileReader();

        reader.readAsText(resData, 'utf-8');
        reader.onload = () => {
            if (!isDownloadSuccess) {
                const { message: msg } = JSON.parse(reader.result);
                message.warning({ content: msg ?? '导出失败', key: 'exportMsgKey' });
                return;
            }
            downloadByBlob(res);
        };

        return isDownloadSuccess;
    } catch (error) {
        message.error({ content: '导出失败', key: 'exportMsgKey' });
        return false;
    }
};

/**
 * 大文件批量下载
 * 默认5w条数据下载一次,数据超过max时，只导出前max条数据，并提示用户联系管理员进行后续操作
 * @name: downloadLargeFile
 * @param {string} url 文件流请求路径
 * @param {object} params 文件流请求参数，需要包含total属性，用于计算分几次下载
 * @param {number} size 每个文件的导出数
 * @param {number} max 最大导出条数
 */
export const downloadLargeFile = async (url, params, method = 'GET', max = 200000, size = 50000, headers = []) => {
    try {
        if (params.total <= 0) {
            message.warn('导出数据为空');
            return;
        }

        const isGtMax = params.total > max;
        const pageNo = Math.ceil((isGtMax ? max : params.total) / size);

        for (const i of Array(pageNo).fill(0).keys()) {
            message.loading({ content: `正在导出第${i + 1}个文件`, key: 'exportMsgKey', duration: 0 });
            const isDownloadSuccess = await downloadFile(url, { ...params, pageNo: i + 1 }, method , headers);

            if (!isDownloadSuccess) {
                return;
            }
        }

        if (isGtMax) {
            message.warn({ content: '当前数据过多，请联系管理员进行后续导出操作', key: 'exportMsgKey' });
        } else {
            message.success({ content: '导出完成', key: 'exportMsgKey' });
        }
    } catch (error) {
        console.log(error);
    }
};


function getFileBlob(url, data = null, config = {}, method){
    return request({
        method,
        url,
        params: data,
        headers: Object.assign(config.headers || {}),
        responseType: 'blob',
        timeout: config.timeout || 0,
    })
}
